package dissertation.services.ejbclass;

import com.intellij.psi.*;

import java.util.Arrays;

import static dissertation.common.constants.Constants.*;

public class EJBClassService implements IEJBClassService {
    @Override
    public PsiClass createClass(PsiDirectory directory, String name) {
        return JavaDirectoryService.getInstance().createClass(directory, name);
    }

    @Override
    public void addEJBClassAnnotation(PsiClass newClass, String annotationString, String ejbName) {
        annotateClass(newClass, annotationString + "(name = \"" + ejbName + "\")");
    }

    @Override
    public void annotateClass(PsiClass newClass, String annotationString) {
        PsiModifierList modifierList = newClass.getModifierList();
        if (modifierList != null) {
            modifierList.addAnnotation(annotationString);
        }
    }

    @Override
    public void addImportStatement(PsiClass newClass, String importString) {
        PsiImportList importList = ((PsiJavaFile) newClass.getContainingFile()).getImportList();
        if (importList != null && importList.findOnDemandImportStatement(importString) == null) {
            PsiImportStatement psiImportStatement = PsiElementFactory.SERVICE.
                    getInstance(newClass.getProject()).createImportStatementOnDemand(importString);
            importList.add(psiImportStatement);
        }
    }

    @Override
    public boolean isEJBClass(PsiClass aClass) {
        PsiAnnotation[] annotations = null;
        if (aClass != null) {
            PsiModifierList modifierList = aClass.getModifierList();
            if (modifierList != null) {
                annotations = modifierList.getAnnotations();
            }
        }

        boolean foundAnnotation = false;

        if (annotations != null) {
            for (PsiAnnotation psiAnnotation : annotations) {
                String qualifiedName = psiAnnotation.getQualifiedName();
                if (Arrays.asList(JAVAX_EJB_STATELESS, JAVAX_EJB_STATEFUL, JAVAX_EJB_SINGLETON, JAVAX_EJB_MESSAGE_DRIVEN).contains(qualifiedName)) {
                    foundAnnotation = true;
                }
            }
        }
        return foundAnnotation;
    }
}
